package com.hll.javaweb.servlet.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hll
 * @create 2022-05-10 13:51
 */
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String action = req.getParameter("action");
    resp.setContentType("text/html; charset=UTF-8");
    switch (action) {
      case "setAttr":
        setSession(req, resp);
        break;
      case "getSessionInfo":
        createOrGetSession(req, resp);
        break;
      case "getAttr":
        getSessionAttr(req, resp);
        break;
      case "expire":
        expire(req, resp);
        break;
    }
  }

  private void setSession(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // 获取了Session的默认超时时长
    req.getSession().setAttribute("key1", "value1");
    resp.getWriter().write("已经往Session中保存了数据");
  }

  private void createOrGetSession(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    // 创建和获取Session会话对象
    HttpSession session = req.getSession();
    // 判断 当前Session会话，是否是新创建出来的
    boolean isNew = session.isNew();
    // 获取Session会话的唯一标识 id
    String id = session.getId();
    int maxInactiveInterval = session.getMaxInactiveInterval();

    resp.getWriter().write("得到的Session，它的id是：" + id + "\n");
    resp.getWriter().write("这个Session是否是新创建的：" + isNew + "\n");
    resp.getWriter().write("Session的默认超时时长为：" + maxInactiveInterval + "\n");
  }

  private void getSessionAttr(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.getWriter().write("key1 = " + req.getSession().getAttribute("key1"));
  }

  private void expire(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpSession session = req.getSession();
    session.invalidate(); // 立即失效
    // session.setMaxInactiveInterval(3); //设置当前Session3秒后超时
    resp.getWriter().write("当前Session已经过期");
  }
}
